package com.chookss.home.interview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.NavigationTools;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.InterviewEntity;
import com.chookss.home.entity.InterviewRecordsEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.RecycleViewDivider;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class InterviewRecordsActivity extends BaseAct {

    @BindView(R.id.tvAllChoice)
    TextView tvAllChoice;
    @BindView(R.id.search_icon)
    ImageView search_icon;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvTimeChoice)
    TextView tvTimeChoice;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llChoice)
    LinearLayout llChoice;
    @BindView(R.id.rcvType)
    RecyclerView rcvType;
    @BindView(R.id.rlType)
    RelativeLayout rlType;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    private MyInterviewAdapter myInterviewAdapter;
    private MyInterviewRecordsAdapter myInterviewRecordsAdapter;
    private List<InterviewEntity> interviewEntities = new ArrayList<>();
    private List<InterviewRecordsEntity> interviewRecordsEntities = new ArrayList<>();
    private String examCode="";//某个试卷的面试记录
    private int type=0;//0所有面试记录1某个试卷的面试记录  2待评价的面试记录
    private int index = 0;//默认选择第一个
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String postCode = "";
    private String createTime="";//当前月份

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_interview_records);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type=getIntent().getIntExtra("type",0);
        examCode=getIntent().getStringExtra("examCode");
        if(type!=0){
            llChoice.setVisibility(View.GONE);
        }
        if(type==2){
            tvTitle.setText("面试评价");
            search_icon.setVisibility(View.GONE);
            NavigationTools.saveUseRecord(this,"2","20");
        }else{
            tvTitle.setText("面试记录");
        }
        rcvType.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rcvType.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myInterviewAdapter = new MyInterviewAdapter(R.layout.item_interview_type, this, interviewEntities);
        rcvType.setAdapter(myInterviewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myInterviewRecordsAdapter = new MyInterviewRecordsAdapter(R.layout.item_interview_records, this, interviewRecordsEntities,type);
        recyclerView.setAdapter(myInterviewRecordsAdapter);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = new Date(System.currentTimeMillis());
        tvTimeChoice.setText(simpleDateFormat.format(date));
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getRecords();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getRecords();
            }
        });
        if(type!=2){
            NavigationTools.setWaterMark(this, "16");
        }
        smrRf.autoRefresh();
        getData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        smrRf.autoRefresh();
    }

    private void getData() {

        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<InterviewEntity>>>() {
        }.getType(), null, Urls.getPostList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<InterviewEntity>>() {
            @Override
            public void onSuccess(List<InterviewEntity> data) {
                if (data != null && data.size() > 0) {
                    interviewEntities.addAll(data);
                    InterviewEntity interviewEntity = new InterviewEntity();
                    interviewEntity.setPostName("全部");
                    interviewEntity.setPostCode("");
                    interviewEntities.add(0, interviewEntity);
                    myInterviewAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }

    private void getRecords() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        String url="";
        if(type==2){
            url=Urls.getUndoInterviewList;
        }else{
            url=Urls.getInterviewPersonList;
            map.put("postCode", postCode);
            map.put("createTime",createTime);
            map.put("examCode",examCode);
            map.put("companyCode",new ShareUtils().getString(this, StaticClass.COMPANYCODE,""));
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<InterviewRecordsEntity>>>() {
        }.getType(), null,url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<InterviewRecordsEntity>>() {
            @Override
            public void onSuccess(List<InterviewRecordsEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    interviewRecordsEntities.clear();
                    myInterviewRecordsAdapter.notifyDataSetChanged();
                }
                if(smrRf==null||llNone==null){
                    return;
                }
                if (data != null && data.size() > 0) {
                    interviewRecordsEntities.addAll(data);
                    myInterviewRecordsAdapter.notifyDataSetChanged();
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (interviewRecordsEntities.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class MyInterviewAdapter extends BaseQuickAdapter<InterviewEntity, BaseViewHolderEx> {
        private Context context;

        public MyInterviewAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<InterviewEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, InterviewEntity item) {

            TextView tvTile = helper.getView(R.id.tvTile);
            ImageView ivChoice = helper.getView(R.id.ivChoice);
            if (index == helper.getItemPosition()) {
                ivChoice.setVisibility(View.VISIBLE);
            } else {
                ivChoice.setVisibility(View.GONE);
            }
            tvTile.setText(item.getPostName());
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    index = helper.getItemPosition();
                    myInterviewAdapter.notifyDataSetChanged();
                    rlType.setVisibility(View.GONE);
                    tvAllChoice.setText(item.getPostName());
                    postCode = item.getPostCode();
                    currentPage = 1;
                    isEnd = false;
                    getRecords();
                }
            });
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;

    private void showDatePickDialog(String curDate) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mYear == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择年月", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear=year;
                        mMonth=month-1;
                        mDay=dayOfMonth;
                        if(mMonth>9){
                            tvTimeChoice.setText(year + "-" + month);
                        }else{
                            tvTimeChoice.setText(year + "-0" + month);
                        }
                        createTime=tvTimeChoice.getText().toString();
                        currentPage = 1;
                        isEnd = false;
                        getRecords();
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDayGone();
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.ivBack, R.id.search_icon, R.id.llTimeChoice, R.id.llAllChoice})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.search_icon:
                startActivity(new Intent(this, InterviewSearchRecordsActivity.class));
                break;
            case R.id.llAllChoice:
                if(rlType==null){
                    return;
                }
                if (rlType.getVisibility() == View.VISIBLE) {
                    rlType.setVisibility(View.GONE);
                } else {
                    if (interviewEntities.size() > 0) {
                        rlType.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case R.id.llTimeChoice:
                if(rlType==null){
                    return;
                }
                showDatePickDialog(tvTimeChoice.getText().toString());
                rlType.setVisibility(View.GONE);
                break;
        }
    }
}
